package com.gaohe.interceptor;

import com.gaohe.common.BaseContext;
import com.gaohe.common.PathMatcher;
import com.gaohe.common.ResultCode;
import com.gaohe.pojo.Admin;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.静态资源  登陆相关  放行
        //获取 uri
        String uri = request.getRequestURI();
        boolean check = PathMatcher.check(uri);
        if (check){
            return true;
        }
        //2.登录了   放行
        Object loginAdmin = request.getSession().getAttribute("loginAdmin");
        if (Objects.nonNull(loginAdmin)){
            //设置线程空间内容
            Admin admin = (Admin) loginAdmin;
            BaseContext.setUsername(admin.getUsername());
            return true;
        }
        //3.没登陆  拦截
        log.info("没有登录，拦截。。。。");
        response.setStatus(ResultCode.NOT_LOGIN);
        return false;
    }
}
